// 插件配置 文件
const logger = require('morgan');
const createError = require('http-errors');
const engine = require('../core/serverEngine');
const cookieParser = require('cookie-parser');
const apiCreateError = require('../core/middlewares/notFoundHandler');

const createLogger = (app) => {
  return logger(app.siteconfig.loggerMode);
};

const createStatic = (app) => {
  return engine.static(app.siteconfig.staticDir);
};

const errorRender = (err, req, res, next) => {
  if (next instanceof Function) {
    next();
  }
  console.log(res.body);
  if (res.body) {
    return;
  }
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
};

const plugins = [
  engine.json(),
  cookieParser(),
  {register: createLogger},
  engine.urlencoded({extended: false}),
  {register: createStatic},
  errorRender, //
  apiCreateError, // catch 404 and forward to error handler
];

module.exports = plugins;